package com.zhou.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhou.entity.Account;
import com.zhou.mapper.AdminMapper;
import com.zhou.service.AdminService;
import com.zhou.utis.booleanUtils.BooleanEaun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.zhou.utis.dto.LoginDto;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service("adminService")
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @Override
    public Integer code(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new RuntimeException("手机号不能穿空");
        }
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getPhone, phone);
        wrapper.eq(Account::getDelFlag, BooleanEaun.FLASE.getResultValue());
        Account account = adminMapper.selectOne(wrapper);
        Random random = new Random();
        int i = random.nextInt(1000 + 9000);
        System.out.println(i);
        //没有查到手机号
        if (StringUtils.isEmpty(account)) {
            String id = UUID.randomUUID().toString();
            Account account1 = new Account();
            account1.setAccountId(id);
            account1.setPhone(phone);
            String add = adminMapper.add(account1);
            if (StringUtils.isEmpty(add)) {
                throw new RuntimeException("手机号注册失败");
            }
            //存入redis缓存 设置2分钟过期时间
            redisTemplate.opsForValue().set("code" + phone, i + "", 2, TimeUnit.MINUTES);
            return i;
        }
        //存入redis缓存 设置2分钟过期时间
        redisTemplate.opsForValue().set("code" + phone, i + "", 2, TimeUnit.MINUTES);
        return i;
    }

    /**
     * 登录接口
     *
     * @param phone
     * @param code
     * @return
     */
    @Override
    public LoginDto login(String phone, String code) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new RuntimeException("参数为空,请重试");
        }
        String msg = redisTemplate.opsForValue().get("code" + phone);
        if (!code.equals(msg)) {
            throw new RuntimeException("验证码不正确，请重试");
        }
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getPhone, phone);
        wrapper.eq(Account::getDelFlag, BooleanEaun.FLASE.getResultValue());
        wrapper.eq(Account::getStatus, BooleanEaun.FLASE.getResultValue());
        Account account = adminMapper.selectOne(wrapper);
        if (StringUtils.isEmpty(account)) {
            throw new RuntimeException("手机号被删除或者不存在请重试");
        }
        //创建token
        String key = "123456";
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("accountId", account.getAccountId());
        String token = JWTUtil.createToken(map, key.getBytes());
        //存redis上，保留时间七天
        redisTemplate.opsForValue().set("token" + token, JSONObject.toJSONString(account), 7, TimeUnit.DAYS);
        LoginDto dto = new LoginDto();
        dto.setToken(token);
        return dto;
    }

    /**
     * 登出
     *
     * @param phone
     * @return
     */
    @Override
    public Boolean out(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new RuntimeException("手机号不能为空");
        }
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getPhone, phone);
        Account account = adminMapper.selectOne(wrapper);
        if (StringUtils.isEmpty(account)) {
            throw new RuntimeException("该手机号不存在");
        }
        Boolean token = redisTemplate.delete("token");
        if (!token) {
            throw new RuntimeException("token清除失败");
        }
        return true;
    }
}
